﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

class StrInFiles
{
    public static void IsStringInFile(string fileName, string pattern)
    {
        using (StreamReader readFile = new StreamReader(new FileStream(fileName, FileMode.Open)))
        {
            while (readFile.Peek() != -1)
            {
                string currentLine = readFile.ReadLine();
                if (currentLine.IndexOf(pattern) >= 0)
                {
                    WriteResultInFile(fileName, currentLine);
                    break;
                }
            }
        }        
    }

    public static void WriteResultInFile(string filePath, string line)
    {
        using (StreamWriter writer = new StreamWriter(new FileStream("result.txt",FileMode.Append)))
        {
            writer.WriteLine(String.Format("FILE: {0}, LINE: \"{1}\"", filePath, line));
        }
    }

    public static void FindResult(string dirName, string pattern)
    {
        if (Directory.Exists(dirName))
        {
            DirectoryInfo dir = new DirectoryInfo(dirName);
            FileInfo[] files = dir.GetFiles();
            DirectoryInfo[] dirs = dir.GetDirectories();
            foreach (FileInfo file in files)
            {                
                if (file.Extension.Equals(".txt") && (file.Name != "result.txt"))
                {
                    IsStringInFile(file.FullName, pattern);                    
                }
            }
            foreach (DirectoryInfo directory in dirs)
            {
                //Console.WriteLine(directory.FullName);
                FindResult(directory.FullName, pattern);
            }
        }
        else
        {
            throw new DirectoryNotFoundException();
        }
    }

    static void Main()
    {
        if (File.Exists("result.txt"))
        {
            File.Delete("result.txt");
        }

        FindResult(@"C:\Users\Academy\Desktop\netessentials\KamenIvanov\Kamen Ivanov\InputOutput", 
            "vidq");
    }
}
